"""
Data formatting utilities for pretty-printing market data
"""

def format_dict_as_table(data_dict: dict, max_rows: int = 5, title: str = "") -> str:
    """
    Format a dictionary of market data as a nice table similar to pandas DataFrame.
    
    Args:
        data_dict: Dictionary with stock codes as keys
        max_rows: Maximum number of rows to display (will show first/last rows)
        title: Optional title for the table
        
    Returns:
        Formatted string table
    """
    if not data_dict:
        return "Empty data"
    
    # Collect all unique keys from the first few items
    all_keys = set()
    sample_items = list(data_dict.items())[:min(10, len(data_dict))]
    for code, value in sample_items:
        if isinstance(value, dict):
            all_keys.update(value.keys())
    
    # Determine columns to display
    priority_cols = ['last_price', 'open', 'high', 'low', 'close', 'volume', 'amount', 'datetime']
    columns = [col for col in priority_cols if col in all_keys]
    # Add any remaining columns
    for col in sorted(all_keys):
        if col not in columns:
            columns.append(col)
    
    # Limit columns to fit in terminal
    columns = columns[:8]
    
    # Calculate column widths
    col_widths = {'code': 12}  # Stock code column
    for col in columns:
        col_widths[col] = max(len(col), 10)
    
    # Build table
    lines = []
    
    if title:
        lines.append(f"\n{'=' * 80}")
        lines.append(f"{title:^80}")
        lines.append(f"{'=' * 80}\n")
    
    # Header
    header_parts = [f"{'Code':<{col_widths['code']}}"]
    for col in columns:
        header_parts.append(f"{col:>{col_widths[col]}}")
    lines.append(" | ".join(header_parts))
    lines.append("-" * (sum(col_widths.values()) + 3 * len(columns)))
    
    # Data rows
    items = list(data_dict.items())
    total_rows = len(items)
    
    if total_rows <= max_rows:
        display_items = items
    else:
        # Show first and last rows with ellipsis in middle
        head_count = max_rows // 2
        tail_count = max_rows - head_count
        display_items = items[:head_count] + [('...', '...')] + items[-tail_count:]
    
    for code, value in display_items:
        if code == '...':
            lines.append(f"{'...':<{col_widths['code']}} | {'...'}")
            continue
            
        if not isinstance(value, dict):
            continue
            
        row_parts = [f"{code:<{col_widths['code']}}"]
        for col in columns:
            val = value.get(col, '')
            if isinstance(val, float):
                formatted = f"{val:>{col_widths[col]}.2f}"
            elif isinstance(val, int):
                formatted = f"{val:>{col_widths[col]},}"
            else:
                formatted = f"{str(val):>{col_widths['code']}}"
            row_parts.append(formatted)
        lines.append(" | ".join(row_parts))
    
    # Footer
    lines.append(f"\n[{total_rows} rows × {len(columns)} columns]")
    
    return "\n".join(lines)


def format_list_as_table(data_list: list, max_rows: int = 5, title: str = "") -> str:
    """
    Format a list of dictionaries as a nice table similar to pandas DataFrame.
    
    Args:
        data_list: List of dictionaries  
        max_rows: Maximum number of rows to display
        title: Optional title for the table
        
    Returns:
        Formatted string table
    """
    if not data_list:
        return "Empty data"
    
    # Convert to dict format with index as key
    data_dict = {f"[{i}]": item for i, item in enumerate(data_list)}
    return format_dict_as_table(data_dict, max_rows, title)
